import React, { useEffect, useRef, useState } from 'react'
import cn from 'classnames'
import mp3 from './sms.mp3'
// import "./index.module.css";
import createContainer from '../createContainer'
import { createPortal } from 'react-dom'
import fetchAxios, { FetchRes, useFetch } from '@/plugins/axios'

export enum Color {
	info = 'notify-info',
	success = 'notify-success',
	warning = 'notify-warning',
	error = 'notify-error',
}
export interface Children {
	title: string
	moid: string
}

export interface NotificatonProps {
	onDelete?: Function
	autoClose?: boolean
	children?: Children
	color?: string
	typeText?: string
	timeDelly?: number
}

const container = createContainer()

const Notification: React.FC<NotificatonProps> = ({
	autoClose = false,
	children,
	color,
	typeText,
	onDelete,
	timeDelly = 10,
}) => {
	const [isClosing, setIsClosing] = useState(false)
	const timeToClose = timeDelly * 1000
	const timeToDelete = 1 * 1000
	const player = useRef<HTMLAudioElement | null>(null)

	useEffect(() => {
		if (isClosing) {
			const timerId = setTimeout(() => setIsClosing(true), timeToDelete)
			return (): void => {
				clearTimeout(timerId)
			}
		}
	}, [isClosing, onDelete])
	useEffect(() => {
		if (autoClose) {
			const timerId = setTimeout(() => setIsClosing(true), timeToClose)
			return () => {
				clearTimeout(timerId)
			}
		}
	}, [autoClose])
	// 已读  改成组件回调函数的形式
	const hadRead = (ids?: string) => {
		fetchAxios({
			url: `/web/messages/states/read`,
			method: 'PUT',
			data: { moids: ids?.split(',') },
		}).then((res) => {
			if (res.success) {
			}
		})
	}
	const handleClose = (id: any) => {
		setIsClosing(true)
		hadRead(id)
	}
	return createPortal(
		<div
			className={cn([
				'container',
				{
					shrink: isClosing,
				},
			])}
		>
			<div className={cn(['notification', { slideIn: !isClosing, slideOut: isClosing }])}>
				<div className="notification-title">消息通知</div>
				<div className="notification-content">
					<a href={`#/alarm`} title={children?.title}>
						您有告警消息，请查看
					</a>
				</div>

				<audio autoPlay ref={player} src={mp3}></audio>
				<button onClick={() => handleClose(children?.moid)} className="closeButton">
					X
				</button>
			</div>
		</div>,
		container
	)
}
export default Notification
